<?php
include_once '../../qc_base.php';
require_once('../../bootstrap.php');
require_once('../../lib/spyc/spyc.php');

function create_table_sets($project_id){

// Get tables which are part of project

$q_projects = Doctrine_Query::create()
->from('Tablesources ts') 
->Where('project_id = ?', $project_id);

$tables = $q_projects->execute();

foreach($tables AS $key=>$table){
	echo 'Tablename is ' . $table->table_name . "<br />\n";

	$q_crudset = Doctrine_Query::create()
	->from('Crudsets cs') 
	->Where('project_id = ?', $project_id)
	->andWhere('main_table = ?', $table->tablesource_id);

	//echo $q_crudset->count();
	//exit;
	
	if($q_crudset->count() == 0){

	
		$newset = new Crudsets();
		$newset->cs_name = $table->table_name;
		$newset->main_table = $table->tablesource_id;
		$newset->project_id = $project_id;
		$newset->save();
		echo 'Created crudset ' . $newset->crudset_id . '  ' . $newset->cs_name . "<br />\n";

		$q_variables = Doctrine_Query::create()
		->from('Variables vars') 
		->Where('project_id = ?', $project_id)
		->andWhere('source_id = ?', $table->tablesource_id);

		$variables = $q_variables->execute();		

		foreach($variables as $vkey=>$variable){
			$newcolumn = new Crudcols();
			$newcolumn->crudset_id = $newset->crudset_id;
			$newcolumn->variable_id = $variable->variable_id;
			$newcolumn->is_key = $variable->is_key;
			$newcolumn->shown_in_list = 1;
			if($variable->is_key == 0){
				$newcolumn->edit_in_list = 1;
			}else{
				$newcolumn->edit_in_list = 0;
			}
			if (strpos($variable->type,'date')) {
				$newcolumn->edit_type = 'cal';
			}else{
			$newcolumn->edit_type = 'text';
			}
			
			
			$newcolumn->col_order = $vkey;
			$newcolumn->makefunction = '';
			$newcolumn->save();
			echo "Created crudcol {$newcolumn->crudcol_id} with variable {$variable->variable_name} <br />\n"; 

		} // end foreach variable


	} // end if crudset for table in project does not exist


}// end for each table
//For each table:

// Does a crudset with that name already exist?

// If not, create a crudset

// get variables of that table

// create crudcol for each variable




}


?>
